from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session
from typing import Optional, Dict, Any
from datetime import datetime
import io

from database import get_db
from services import report_service, file_service
import schemas

router = APIRouter()

# 统一响应格式
def create_response(code: int = 200, message: str = "成功", data: Any = None):
    return {
        "code": code,
        "message": message,
        "data": data
    }

@router.post("/create", response_model=schemas.Response)
async def create_report(
    report: schemas.ReportCreate,
    db: Session = Depends(get_db)
):
    """
    创建报告
    
    - **merchant_id**: 商户ID
    - **report_name**: 报告名称
    - **report_date**: 报告日期
    - **expected_file_count**: 预期文件数量
    - **remark**: 备注信息
    """
    try:
        report_dict = report.dict()
        report_dict["operator"] = "system"
        
        result = report_service.create_report(db, report_dict)
        
        return create_response(
            message="创建成功",
            data={
                "reportId": result.id,
                "reportCode": result.report_code,
                "merchantId": result.merchant_id,
                "merchantName": result.merchant.name if result.merchant else None,
                "reportName": result.report_name,
                "reportDate": result.report_date.strftime("%Y-%m-%d"),
                "status": result.status,
                "fileCount": result.file_count,
                "expectedFileCount": result.expected_file_count,
                "createTime": result.created_at.strftime("%Y-%m-%d %H:%M:%S")
            }
        )
    except Exception as e:
        return create_response(code=500, message=f"创建失败: {str(e)}")

@router.get("/list", response_model=schemas.Response)
async def list_reports(
    merchant_id: Optional[int] = None,
    status: Optional[int] = None,
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
    page_num: int = 1,
    page_size: int = 10,
    db: Session = Depends(get_db)
):
    """
    获取报告列表
    
    - **merchant_id**: 商户ID
    - **status**: 报告状态：0-未完成，1-部分完成，2-已完成
    - **start_date**: 开始日期，格式：yyyy-MM-dd
    - **end_date**: 结束日期，格式：yyyy-MM-dd
    - **page_num**: 页码，从1开始，默认1
    - **page_size**: 每页记录数，默认10
    """
    try:
        filters = {
            "merchant_id": merchant_id,
            "status": status
        }
        # 移除None值
        filters = {k: v for k, v in filters.items() if v is not None}
        
        # 处理日期范围
        date_range = {}
        if start_date:
            date_range["start_date"] = datetime.strptime(start_date, "%Y-%m-%d").date()
        if end_date:
            date_range["end_date"] = datetime.strptime(end_date, "%Y-%m-%d").date()
        
        result = report_service.get_report_list(db, filters, date_range, page_num, page_size)
        
        return create_response(
            message="查询成功",
            data=result
        )
    except Exception as e:
        return create_response(code=500, message=f"查询失败: {str(e)}")

@router.get("/{report_id}", response_model=schemas.Response)
async def get_report(
    report_id: int,
    db: Session = Depends(get_db)
):
    """
    获取报告详情
    
    - **report_id**: 报告ID
    """
    try:
        result = report_service.get_report_detail(db, report_id)
        if not result:
            return create_response(code=404, message="报告不存在")
        
        return create_response(
            message="查询成功",
            data=result
        )
    except Exception as e:
        return create_response(code=500, message=f"查询失败: {str(e)}")

@router.get("/integrated/{report_id}")
async def download_integrated_report(
    report_id: int,
    db: Session = Depends(get_db)
):
    """
    下载整合报告
    
    - **report_id**: 报告ID
    """
    try:
        report_info = report_service.get_integrated_report(db, report_id)
        if not report_info:
            raise HTTPException(status_code=404, detail="整合报告不存在")
        
        file_data = None
        if report_info["store_type"] == 1:
            # 数据库存储
            file_data = report_info["report_content"]
        else:
            # 文件系统存储
            file_data = file_service.read_from_filesystem(report_info["file_path"])
        
        # 确定内容类型
        content_type = file_service.get_content_type(report_info["file_format"])
        
        # 创建响应
        return StreamingResponse(
            io.BytesIO(file_data),
            media_type=content_type,
            headers={
                "Content-Disposition": f'attachment; filename="{report_info["file_name"]}"'
            }
        )
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"下载失败: {str(e)}") 